package com.itboy.mall.wms.warepurchase.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itboy.common.exception.CustomException;
import com.itboy.common.utils.PageUtils;
import com.itboy.common.core.page.PagePlus;
import com.itboy.common.core.page.TableDataInfo;
import com.itboy.mall.wms.warepurchase.constant.WareConstant;
import com.itboy.mall.wms.warepurchasedetail.domain.MallWarePurchaseDetail;
import com.itboy.mall.wms.warepurchasedetail.service.IMallWarePurchaseDetailService;
import com.itboy.mall.wms.waresku.domain.MallWareSku;
import com.itboy.mall.wms.waresku.service.IMallWareSkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.itboy.common.core.mybatisplus.core.ServicePlusImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itboy.mall.wms.warepurchase.bo.MallWarePurchaseAddBo;
import com.itboy.mall.wms.warepurchase.bo.MallWarePurchaseQueryBo;
import com.itboy.mall.wms.warepurchase.bo.MallWarePurchaseEditBo;
import com.itboy.mall.wms.warepurchase.domain.MallWarePurchase;
import com.itboy.mall.wms.warepurchase.mapper.MallWarePurchaseMapper;
import com.itboy.mall.wms.warepurchase.vo.MallWarePurchaseVo;
import com.itboy.mall.wms.warepurchase.service.IMallWarePurchaseService;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 采购信息Service业务层处理
 *
 * @author itboy
 * @date 2021-08-10
 */
@Service
public class MallWarePurchaseServiceImpl extends ServicePlusImpl<MallWarePurchaseMapper, MallWarePurchase> implements IMallWarePurchaseService {

	@Autowired
	private IMallWarePurchaseDetailService iMallWarePurchaseDetailService;
	@Autowired
	private IMallWarePurchaseService iMallWarePurchaseService;

	@Autowired
	private IMallWareSkuService iMallWareSkuService;
    @Override
    public MallWarePurchaseVo queryById(Long id){
        return getVoById(id, MallWarePurchaseVo.class);
    }

    @Override
    public TableDataInfo<MallWarePurchaseVo> queryPageList(MallWarePurchaseQueryBo bo) {
        PagePlus<MallWarePurchase, MallWarePurchaseVo> result = pageVo(PageUtils.buildPagePlus(), buildQueryWrapper(bo), MallWarePurchaseVo.class);
        return PageUtils.buildDataInfo(result);
    }

    @Override
    public List<MallWarePurchaseVo> queryList(MallWarePurchaseQueryBo bo) {
        return listVo(buildQueryWrapper(bo), MallWarePurchaseVo.class);
    }

    private LambdaQueryWrapper<MallWarePurchase> buildQueryWrapper(MallWarePurchaseQueryBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<MallWarePurchase> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getAssigneeId() != null, MallWarePurchase::getAssigneeId, bo.getAssigneeId());
        lqw.like(StrUtil.isNotBlank(bo.getAssigneeName()), MallWarePurchase::getAssigneeName, bo.getAssigneeName());
        lqw.like(StrUtil.isNotBlank(bo.getPhone()), MallWarePurchase::getPhone, bo.getPhone());
        lqw.eq(bo.getPriority() != null, MallWarePurchase::getPriority, bo.getPriority());
        lqw.eq(bo.getStatus() != null, MallWarePurchase::getStatus, bo.getStatus());
        lqw.eq(bo.getWareId() != null, MallWarePurchase::getWareId, bo.getWareId());
        return lqw;
    }

    @Override
    public Boolean insertByAddBo(MallWarePurchaseAddBo bo) {
        MallWarePurchase add = BeanUtil.toBean(bo, MallWarePurchase.class);
        validEntityBeforeSave(add);
        return save(add);
    }

    @Override
    public Boolean updateByEditBo(MallWarePurchaseEditBo bo) {
        MallWarePurchase update = BeanUtil.toBean(bo, MallWarePurchase.class);
        validEntityBeforeSave(update);
        return updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(MallWarePurchase entity){
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return removeByIds(ids);
    }

	@Override
	public List<MallWarePurchase> unreceive() {
		LambdaQueryWrapper<MallWarePurchase> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(MallWarePurchase::getStatus, WareConstant.PurchaseStatusEnum.CREATED).or().
			         eq(MallWarePurchase::getStatus, WareConstant.PurchaseStatusEnum.ASSIGNED);
		List<MallWarePurchase> mallWarePurchases = this.baseMapper.selectList(queryWrapper);
		return mallWarePurchases;
	}

	@Override
	@Transactional
	public Boolean updateAssignWarePurchase(MallWarePurchaseEditBo bo) {
		MallWarePurchase mallWarePurchase = this.baseMapper.selectById(bo.getId());

		if(mallWarePurchase.getStatus().equals(WareConstant.PurchaseStatusEnum.RECEIVED.getCode())){
			throw new CustomException("采购单"+WareConstant.PurchaseStatusEnum.RECEIVED.getMessage());
		}else if(mallWarePurchase.getStatus().equals(WareConstant.PurchaseStatusEnum.FINISH.getCode())){
			throw new CustomException("采购单"+WareConstant.PurchaseStatusEnum.FINISH.getMessage());
		}else if(mallWarePurchase.getStatus().equals(WareConstant.PurchaseStatusEnum.HASEERROR.getCode())){
			throw new CustomException("采购单"+WareConstant.PurchaseStatusEnum.HASEERROR.getMessage());
		}
		mallWarePurchase.setAssigneeId(bo.getAssigneeId());
		mallWarePurchase.setAssigneeName(bo.getAssigneeName());
		mallWarePurchase.setStatus(WareConstant.PurchaseStatusEnum.ASSIGNED.getCode());
		LambdaUpdateWrapper<MallWarePurchase> queryWrapper = new LambdaUpdateWrapper<>();
		queryWrapper.eq(MallWarePurchase::getId,bo.getId());
		queryWrapper.set(MallWarePurchase::getPhone,bo.getPhone());
		int update = this.baseMapper.update(mallWarePurchase,queryWrapper);
		if(update==1){
			return true;
		}
		return false;
	}

	@Override
	@Transactional
	public Boolean receivePurchase(MallWarePurchaseEditBo bo) {
    	//1.领取采购单
		MallWarePurchase mallWarePurchase = this.baseMapper.selectById(bo.getId());
		if(mallWarePurchase.getStatus().equals(WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())){
			mallWarePurchase.setStatus(WareConstant.PurchaseStatusEnum.RECEIVED.getCode());
			this.baseMapper.updateById(mallWarePurchase);
		}else if(mallWarePurchase.getStatus().equals(WareConstant.PurchaseStatusEnum.RECEIVED.getCode())){
			throw new CustomException("采购单"+WareConstant.PurchaseStatusEnum.RECEIVED.getMessage());
		}else if(mallWarePurchase.getStatus().equals(WareConstant.PurchaseStatusEnum.FINISH.getCode())){
			throw new CustomException("采购单"+WareConstant.PurchaseStatusEnum.FINISH.getMessage());
		}else if(mallWarePurchase.getStatus().equals(WareConstant.PurchaseStatusEnum.HASEERROR.getCode())){
			throw new CustomException("采购单"+WareConstant.PurchaseStatusEnum.HASEERROR.getMessage());
		}
		//2.修改采购明细单状态 改为正在采购
		LambdaUpdateWrapper<MallWarePurchaseDetail> queryWrapper = new LambdaUpdateWrapper<>();
		queryWrapper.eq(MallWarePurchaseDetail::getPurchaseId,mallWarePurchase.getId());
		queryWrapper.set(MallWarePurchaseDetail::getStatus,WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
		return iMallWarePurchaseDetailService.update(queryWrapper);
	}

	@Override
	@Transactional
	public Boolean finishPurchaseOrder(MallWarePurchaseEditBo bo) {
    	if(bo.getIds().length>0){
    		//1.查询采购单
			LambdaQueryWrapper<MallWarePurchase> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.in(MallWarePurchase::getId, Arrays.asList(bo.getIds()));
			List<MallWarePurchase> mallWarePurchaseList = this.baseMapper.selectList(queryWrapper);
			if(CollectionUtil.isNotEmpty(mallWarePurchaseList)){
				//已领取的集合
				List<MallWarePurchase> warePurchaseList = mallWarePurchaseList.stream()
				.filter(e -> e.getStatus().equals(WareConstant.PurchaseStatusEnum.RECEIVED.getCode())).map(item->{
						item.setStatus(WareConstant.PurchaseStatusEnum.FINISH.getCode());
						return item;
					}).collect(Collectors.toList());
				//2.改变采购单状态
				boolean b = iMallWarePurchaseService.updateBatchById(warePurchaseList);
				if(!b){
					throw new CustomException("改变采购单状态失败");
				}
				//3.查询采购明细状态
				List<Long> purchaseIds = mallWarePurchaseList.stream().map(e -> e.getId()).collect(Collectors.toList());
				LambdaQueryWrapper<MallWarePurchaseDetail> qw = new LambdaQueryWrapper<>();
				qw.in(MallWarePurchaseDetail::getPurchaseId,purchaseIds);
				List<MallWarePurchaseDetail> mallWarePurchaseDetailList = iMallWarePurchaseDetailService.list(qw);
				if(CollectionUtil.isNotEmpty(mallWarePurchaseDetailList)){
					//正在采购的集合
					List<MallWarePurchaseDetail> warePurchaseDetailList = mallWarePurchaseDetailList.stream()
						.filter(e -> e.getStatus().equals(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode())).map(item -> {
							item.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
							return item;
						}).collect(Collectors.toList());
					//4.改变采购明细状态
					boolean batch = iMallWarePurchaseDetailService.updateBatchById(warePurchaseDetailList);
					if(!batch){
						throw new CustomException("改变采购明细状态失败");
					}
					//5.放入库存
					List<MallWareSku> mallWareSkuList = new ArrayList<>();
					warePurchaseDetailList.forEach(e->{
						LambdaQueryWrapper<MallWareSku> lqw = new LambdaQueryWrapper<>();
						lqw.eq(MallWareSku::getSkuId,e.getSkuId());
						lqw.eq(MallWareSku::getWareId,e.getWareId());
						MallWareSku mallWareSku = iMallWareSkuService.getOne(lqw);
						if(ObjectUtil.isNotNull(mallWareSku)){
							mallWareSku.setStock(mallWareSku.getStock()+e.getSkuNum());
							mallWareSkuList.add(mallWareSku);
						}
					});
                     //6.保存库存
					if(CollectionUtil.isNotEmpty(mallWareSkuList)){
						boolean batchById = iMallWareSkuService.saveOrUpdateBatch(mallWareSkuList);
						if(!batchById){
							throw new CustomException("保存库存失败");
						}
					}else{
						throw new CustomException("保存库存失败");
					}
					return true;

				}else{
					throw new CustomException("未关联采购明细");
				}
			}
		}

		return false;
	}
}
